package com.weimei.conversionTreasure.activity;

import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.chad.library.BR;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.weimei.conversionTreasure.R;
import com.weimei.conversionTreasure.app.AppViewModelFactory;
import com.weimei.conversionTreasure.databinding.ActivityAddPfBinding;
import com.weimei.conversionTreasure.utils.GlideEngine;
import com.weimei.conversionTreasure.utils.ValidateUtils;
import com.weimei.conversionTreasure.utils.permission.RxPermissionsUtils;
import com.weimei.conversionTreasure.viewModel.AddPfVM;
import com.weimei.conversionTreasure.weight.richEditText.utils.KeyBoardUtils;
import com.weimei.conversionTreasure.weight.richEditText.view.RichEditor;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AddPfActivity extends BaseActivity<ActivityAddPfBinding, AddPfVM> {

    private boolean showOp = true;
    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_add_pf;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public AddPfVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, (ViewModelProvider.Factory) factory).get(AddPfVM.class);
    }

    String title,content,id;
    @Override
    public void initParam() {
        super.initParam();
        id = getIntent().getStringExtra("id");
        title = getIntent().getStringExtra("title");
        content = getIntent().getStringExtra("content");
    }

    private void againEdit() {
        //如果第一次点击例如加粗，没有焦点时，获取焦点并弹出软键盘
        binding.richEditor.focusEditor();
        KeyBoardUtils.openKeybord(binding.editName, AddPfActivity.this);
    }

    @Override
    public void initData() {
        super.initData();
        initEditor();
        initRichView();

        if (ValidateUtils.isNotEmptyString(id)){
            viewModel.sid.set(id);
        }

        binding.back.setOnClickListener(v -> finish());
        binding.save.setOnClickListener(v -> {
            if (ValidateUtils.isEmptyString(binding.editName.getText().toString())){
                ToastUtils.showShort("请输入配方标题");
                return;
            }
            if (ValidateUtils.isEmptyString(binding.richEditor.getHtml())){
                ToastUtils.showShort("请输入配方内容");
                return;
            }

            viewModel.pulish(binding.editName.getText().toString().trim(),binding.richEditor.getHtml());
        });

        if (ValidateUtils.isNotEmptyString(title)){
            binding.editName.setText(title);
        }

        if (ValidateUtils.isNotEmptyString(content)){
            binding.richEditor.setHtml(content);
        }


    }

    private void initEditor() {
        //输入框显示字体的大小
        binding.richEditor.setEditorFontSize(18);
        //输入框显示字体的颜色
        binding.richEditor.setEditorFontColor(Color.BLACK);
        //输入框背景设置
        binding.richEditor.setEditorBackgroundColor(Color.WHITE);
        //输入框文本padding
        binding.richEditor.setPadding(10, 10, 10, 10);
        //输入提示文本
        binding.richEditor.setPlaceholder("请开始你的创作！~");

        //文本输入框监听事件
        binding.richEditor.setOnTextChangeListener(new RichEditor.OnTextChangeListener() {
            @Override
            public void onTextChange(String text) {
                Log.e("富文本文字变动", text);
//                if (TextUtils.isEmpty(binding.editName.getText().toString().trim())) {
//                    binding.txtPublish.setSelected(false);
//                    binding.txtPublish.setEnabled(false);
//                    return;
//                }
//
//                if (TextUtils.isEmpty(text)) {
//                    binding.txtPublish.setSelected(false);
//                    binding.txtPublish.setEnabled(false);
//                } else {
//
//                    if (TextUtils.isEmpty(Html.fromHtml(text))) {
//                        binding.txtPublish.setSelected(false);
//                        binding.txtPublish.setEnabled(false);
//                    } else {
//                        binding.txtPublish.setSelected(true);
//                        binding.txtPublish.setEnabled(true);
//                    }
//
//                }

            }
        });

        binding.editName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String html = binding.richEditor.getHtml();

//                if (TextUtils.isEmpty(html)) {
//                    binding.txtPublish.setSelected(false);
//                    binding.txtPublish.setEnabled(false);
//                    return;
//                } else {
//                    if (TextUtils.isEmpty(Html.fromHtml(html))) {
//                        binding.txtPublish.setSelected(false);
//                        binding.txtPublish.setEnabled(false);
//                        return;
//                    } else {
//                        binding.txtPublish.setSelected(true);
//                        binding.txtPublish.setEnabled(true);
//                    }
//                }


//                if (TextUtils.isEmpty(s.toString())) {
//                    binding.txtPublish.setSelected(false);
//                    binding.txtPublish.setEnabled(false);
//                } else {
//                    binding.txtPublish.setSelected(true);
//                    binding.txtPublish.setEnabled(true);
//                }


            }
        });

        binding.richEditor.setOnDecorationChangeListener((text, types) -> {
            ArrayList<String> flagArr = new ArrayList<>();
            for (int i = 0; i < types.size(); i++) {
                flagArr.add(types.get(i).name());
            }

            if (flagArr.contains("ITALIC")) {
                binding.richView.ivQx.setImageResource(R.mipmap.ic_font_x_pf_s);
            } else {
                binding.richView.ivQx.setImageResource(R.mipmap.ic_font_x_pf);
            }


            if (flagArr.contains("BOLD")) {
                binding.richView.ivBold.setImageResource(R.mipmap.ic_font_pf_s);
            } else {
                binding.richView.ivBold.setImageResource(R.mipmap.ic_font_pf);
            }

            if (flagArr.contains("UNDERLINE")) {
                binding.richView.ivXhx.setImageResource(R.mipmap.ic_font_xh_pf_s);
            } else {
                binding.richView.ivXhx.setImageResource(R.mipmap.ic_font_xh_pf);
            }

            if (flagArr.contains("STRIKETHROUGH")) {
                binding.richView.ivScx.setImageResource(R.mipmap.ic_font_z_pf_s);
            } else {
                binding.richView.ivScx.setImageResource(R.mipmap.ic_font_z_pf);
            }

            if (flagArr.contains("ORDEREDLIST")) {
                binding.richView.ivBt1.setImageResource(R.mipmap.icon_list_def1_s);
                binding.richView.ivBt2.setImageResource(R.mipmap.icon_list_def);
            } else {
                binding.richView.ivBt1.setImageResource(R.mipmap.icon_list_def1);
            }

            if (flagArr.contains("UNORDEREDLIST")) {
                binding.richView.ivBt1.setImageResource(R.mipmap.icon_list_def1);
                binding.richView.ivBt2.setImageResource(R.mipmap.icon_list_def_s);
            } else {
                binding.richView.ivBt2.setImageResource(R.mipmap.icon_list_def);
            }


        });


        binding.richEditor.setImageClickListener(new RichEditor.ImageClickListener() {
            @Override
            public void onImageClick(String imageUrl) {
//                currentUrl = imageUrl;
//                popupWindow.showBottom(binding.getRoot(), 0.5f);
            }
        });


    }

    private void initRichView() {
        binding.richView.ivJp.setOnClickListener(view -> {
            againEdit();
        });

        binding.richView.ivXl.setOnClickListener(view -> {
            if (showOp){
                showOp = false;
                binding.richView.llOp.setVisibility(View.VISIBLE);
            }else {
                showOp = true;
                binding.richView.llOp.setVisibility(View.GONE);

            }
        });

        binding.richView.ivDl.setOnClickListener(view -> {
            binding.richView.llOp.setVisibility(View.VISIBLE);
            binding.richView.bt.setVisibility(View.VISIBLE);
        });

        binding.richView.ivImg.setOnClickListener(view -> {
            RxPermissionsUtils.file(AddPfActivity.this, (RxPermissionsUtils.Accept) () -> {
                PictureSelector.create(AddPfActivity.this)
                        .openGallery(SelectMimeType.ofImage())
                        .isDisplayCamera(false)
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(1)
                        .setMinSelectNum(1)
                        .setImageSpanCount(4)
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                againEdit();
                                binding.richEditor.insertImage(result.get(0).getPath(),"",30);
                                KeyBoardUtils.openKeybord(binding.editName, AddPfActivity.this);
                                binding.richEditor.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (binding.richEditor != null) {
                                            binding.richEditor.scrollToBottom();
                                        }
                                    }
                                }, 200);
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
            });
        });

        binding.richView.ivBold.setOnClickListener(view -> {
            againEdit();
            binding.richEditor.setBold();
        });

        binding.richView.ivQx.setOnClickListener(view -> {
            againEdit();
            binding.richEditor.setItalic();
        });

        binding.richView.ivXhx.setOnClickListener(view -> {
            againEdit();
            binding.richEditor.setUnderline();
        });

        binding.richView.ivScx.setOnClickListener(view -> {
            againEdit();
            binding.richEditor.setStrikeThrough();
        });

        binding.richView.ivBt1.setOnClickListener(view -> {
            againEdit();
            binding.richEditor.setNumbers();
        });

        binding.richView.ivBt2.setOnClickListener(view -> {
            againEdit();
            binding.richEditor.setBullets();
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        KeyBoardUtils.closeKeybord(binding.editName,this);
    }
}